<?php

namespace App\Http\Controllers\Api\V1;


use App\Http\Resources\BookChaptersResource;
use App\Models\BookChapters;
use App\Models\BookHistory;
use Illuminate\Http\Request;

/***
 * 书籍章节
 * Class BookChaptersController
 * @package App\Http\Controllers\Api\V1
 */
class BookChaptersController extends ApiController
{
    public function list(BookChapters $chapters, Request $request)
    {
        $model = $chapters->newQuery();
        //获取单本目录
        if ($request->has('book_id') && !empty($request->book_id)) {
            $model->where('book_id', $request->book_id);
        }
        //排序
        if ($request->has('sort') && !empty($request->sort) && $request->sort == 1) {
            $model->orderBy('sort', 'asc');
        } else if ($request->has('sort') && !empty($request->sort) && $request->sort == 2) {
            $model->orderBy('sort', 'desc');
        }
        if (empty($request->input())) {
            $list = [];
        } else {
            $model->with('book');
            $list = $model->where('status', 2)->paginate();
        }
        return $this->success('成功', BookChaptersResource::collection($list));
    }

    public function getinfo(Request $request)
    {
        if (!$request->has('id') || empty($request->id)) {
            return $this->error('参数错误');
        }
        $data = BookChapters::with('book')->find($request->id);
        //如果是登录用户就加入到阅读历史
        if ($data && $this->getUserId() != 0) {
            $history = BookHistory::updateOrCreate([
                'module_id' => $data->book->module_id,
                'user_id' => $this->getUserId(),
                'book_id' => $data->book->id,
            ], ['chapters_id' => $request->input('id')]);
        }
        return $this->success('成功', BookChaptersResource::make($data));
    }
}
